package com.mrd.shiptask_shipowner.activity;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.json.JSONArray;

import com.mrd.shiptask_shipowner.R;
import com.mrd.shiptask_shipowner.constants.database.DBUtil;
import com.mrd.shiptask_shipowner.serviecs.initdatadao.InitDatasDaoImpl;
import com.mrd.shiptask_shipowner.shiareutil.SharePreferenceUtil;
import com.mrd.shiptask_shipowner.unit_tools.DatasTools;
import com.mrd.shiptask_shipowner.unit_tools.FunctionOfActivity;
import com.mrd.shiptask_shipowner.unit_tools.SysApplication;
import com.mrd.shiptask_shipowner.unit_tools.flesh_listview.MyListView;
import com.mrd.shiptask_shipowner.unit_tools.flesh_listview.MyListView.OnRefreshListener;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.app.ProgressDialog;
import android.app.DatePickerDialog.OnDateSetListener;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.TextView;

public class ShipOrderActivity extends Activity {

	private final ShipOrderActivity THIS = ShipOrderActivity.this;
	private List<Map<String, Object>> mData;
	private MyAdapter adapter;
	private Button newShipOrderBt;
	private Button backToBeforeBt;
	private SharePreferenceUtil spu;
	ProgressDialog progressDialog;

	@SuppressLint("SimpleDateFormat")
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_ship_order);
		spu = new SharePreferenceUtil(THIS, "saveUser");
		setInitDatas();
		SysApplication.getInstance().addActivity(this);
	}

	public void setInitDatas() {
		progressDialog = new ProgressDialog(THIS);
		initListView();
		initViewAction();
	}

	private void initListView() {
		try {
			JSONArray jas = DBUtil.selectShipOrderTableByStatus(THIS,
					spu.getShip_id());
			spu.getShip_name();
			List<Map<String, Object>> mapList = new ArrayList<Map<String, Object>>();
			for (int i = 0; i < jas.length(); i++) {
				Map<String, Object> map = new HashMap<String, Object>();
				String getId = DatasTools.getJsonValue(jas.getJSONObject(i),
						"ID");
				String getStatus = DatasTools.getJsonValue(
						jas.getJSONObject(i), "STATUS");
				String getStartPort = DatasTools.getJsonValue(
						jas.getJSONObject(i), "START_PORT");
				String getEndPort = DatasTools.getJsonValue(
						jas.getJSONObject(i), "END_PORT");
				String getEShipPort = DatasTools.getJsonValue(
						jas.getJSONObject(i), "EMPTY_SHIP_PORT");
				String getEShipTime = DatasTools.getJsonValue(
						jas.getJSONObject(i), "ENPTY_SHIP_DATE");
				String getEndTime = DatasTools.getJsonValue(
						jas.getJSONObject(i), "EFFECTIVE_DATE");
				String getValid = DatasTools.getJsonValue(jas.getJSONObject(i),
						"VALID");
				String getYanQi = DatasTools.getJsonValue(jas.getJSONObject(i),
						"YANQI");
				String getLoadton = DatasTools.getJsonValue(
						jas.getJSONObject(i), "GOODS_COUNT_UNIT");
				String getGoodsType = DatasTools.getJsonValue(
						jas.getJSONObject(i), "GOODS_TYPE");
				String getMinPice = DatasTools.getJsonValue(
						jas.getJSONObject(i), "MIN_PICE");
				String getMaxPice = DatasTools.getJsonValue(
						jas.getJSONObject(i), "MAX_PICE");
				map.put("getId", getId);
				map.put("getStatus", getStatus);
				map.put("getStartPort", getStartPort);
				map.put("getEndPort", getEndPort);
				map.put("getEShipPort", getEShipPort);
				map.put("getEShipTime", getEShipTime);
				map.put("getEndTime", getEndTime);
				map.put("getValid", getValid);
				map.put("getYanQi", getYanQi);
				map.put("getLoadton", getLoadton);
				map.put("getGoodsType", getGoodsType);
				map.put("getMinPice", getMinPice);
				map.put("getMaxPice", getMaxPice);
				mapList.add(map);
			}

			final MyListView listView = (MyListView) findViewById(R.id.listView1);
			// 生成动态数组，并且转入数据
			mData = mapList;
			// 生成适配器的ImageItem <====> 动态数组的元素，两者一一对应
			adapter = new MyAdapter(this);
			listView.setAdapter(adapter);
			listView.setonRefreshListener(new OnRefreshListener() {

				@Override
				public void onRefresh() {
					new AsyncTask<Void, Void, Void>() {
						@Override
						protected Void doInBackground(Void... params) {
							try {
								InitDatasDaoImpl.getShipOrderDatas(THIS);
								Thread.sleep(2000);
							} catch (Exception e) {
								e.printStackTrace();
							}
							return null;
						}

						@Override
						protected void onPostExecute(Void result) {
							adapter.notifyDataSetChanged();
							listView.onRefreshComplete();
						}
					}.execute(null, null, null);
				}
			});
		} catch (Exception e) {
		}
	}

	private void initViewAction() {
		TextView topTitleTv = (TextView) findViewById(R.id.topTitleTv);
		topTitleTv.setText("发布船源");
		newShipOrderBt = (Button) findViewById(R.id.new_ship_order_bt);
		newShipOrderBt.setOnClickListener(socl);

		backToBeforeBt = (Button) findViewById(R.id.backToBeforeBt10);
		backToBeforeBt.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				FunctionOfActivity.progressDialogShow(THIS);
				startActivity(new Intent(THIS, MainActivity.class));
			}
		});
	}

	public final OnClickListener socl = new OnClickListener() {

		@Override
		public void onClick(View arg0) {
			switch (arg0.getId()) {
			case R.id.new_ship_order_bt:
				FunctionOfActivity.progressDialogShow(THIS);
				Intent intent = new Intent(THIS, NewShipOrderActivity.class);
				startActivity(intent);

				break;

			default:
				break;
			}
		}

	};

	public final class ViewHolder {
		private TextView jichuangangtext, jichuanshijiant, huowut, qiyundit,
				mudidit, youxiaoshijiant, caozuolant, dunweit, priceinterval;
		private Button yanqib, yipeihuob, bianjib, tijiaob;
	}

	public class MyAdapter extends BaseAdapter {

		private final LayoutInflater mInflater;

		public MyAdapter(Context context) {
			this.mInflater = LayoutInflater.from(context);
		}

		@Override
		public int getCount() {
			// TODO Auto-generated method stub
			return mData.size();
		}

		@Override
		public Object getItem(int arg0) {
			// TODO Auto-generated method stub
			return null;
		}

		@Override
		public long getItemId(int arg0) {
			// TODO Auto-generated method stub
			return 0;
		}

		@SuppressLint({ "NewApi", "ResourceAsColor" })
		@Override
		public View getView(final int position, View convertView,
				ViewGroup parent) {

			ViewHolder holder = null;

			holder = new ViewHolder();
			if (convertView == null) {
				convertView = mInflater.inflate(
						R.layout.activity_ship_order_listitem, null);
				holder.jichuangangtext = (TextView) convertView
						.findViewById(R.id.jichuangangtv);
				holder.jichuanshijiant = (TextView) convertView
						.findViewById(R.id.jichuanshijiantv);
				holder.huowut = (TextView) convertView
						.findViewById(R.id.huowutv);
				holder.qiyundit = (TextView) convertView
						.findViewById(R.id.qiyunditv);
				holder.mudidit = (TextView) convertView
						.findViewById(R.id.mudiditv);
				holder.youxiaoshijiant = (TextView) convertView
						.findViewById(R.id.youxiaoshijiantv);
				holder.yanqib = (Button) convertView.findViewById(R.id.yanqibt);
				holder.yipeihuob = (Button) convertView
						.findViewById(R.id.yipeihuobt);
				holder.caozuolant = (TextView) convertView
						.findViewById(R.id.caozuolantv);
				holder.bianjib = (Button) convertView
						.findViewById(R.id.bianjibt);
				holder.tijiaob = (Button) convertView
						.findViewById(R.id.tijiaobt);
				holder.dunweit = (TextView) convertView
						.findViewById(R.id.dunweitv);
				holder.priceinterval = (TextView) convertView
						.findViewById(R.id.priceintervaltv);

				convertView.setTag(holder);
			} else {
				holder = (ViewHolder) convertView.getTag();
			}
			String EShipPort = mData.get(position).get("getEShipPort")
					.toString();
			String EShipTime = mData.get(position).get("getEShipTime")
					.toString();
			String GoodsType = mData.get(position).get("getGoodsType")
					.toString();
			String StartPort = mData.get(position).get("getStartPort")
					.toString();
			String EndPort = mData.get(position).get("getEndPort").toString();
			String EndTime = mData.get(position).get("getEndTime").toString();
			String loadton = mData.get(position).get("getLoadton").toString();
			String priceinterval = "";
			// 填写了小价格区间为true
			boolean isInfoedMinPice = mData.get(position).get("getMinPice")
					.toString().length() > 0;
			// 填写了大价格区间为true
			boolean isInfoedMaxPice = mData.get(position).get("getMaxPice")
					.toString().length() > 0;
			if (isInfoedMinPice || isInfoedMaxPice) {
				if (isInfoedMinPice && isInfoedMaxPice) {
					priceinterval = mData.get(position).get("getMinPice")
							.toString()
							+ " - "
							+ mData.get(position).get("getMaxPice").toString()
							+ " (元/吨)";
				} else if (isInfoedMinPice && !isInfoedMaxPice) {
					priceinterval = mData.get(position).get("getMinPice")
							.toString()
							+ " (元/吨)起";
				} else if (!isInfoedMinPice && isInfoedMaxPice) {
					priceinterval = mData.get(position).get("getMaxPice")
							.toString()
							+ " (元/吨)以下";
				}
			}
			holder.jichuangangtext.setText(EShipPort);
			holder.jichuanshijiant.setText(EShipTime);
			holder.huowut.setText(GoodsType);
			holder.qiyundit.setText(StartPort);
			holder.mudidit.setText(EndPort);
			holder.youxiaoshijiant.setText(EndTime);
			holder.dunweit.setText(loadton);
			holder.priceinterval.setText(priceinterval);
			// 初始隐藏按钮
			holder.yanqib.setVisibility(View.GONE);
			holder.yipeihuob.setVisibility(View.GONE);
			holder.caozuolant.setVisibility(View.GONE);
			holder.bianjib.setVisibility(View.GONE);
			holder.tijiaob.setVisibility(View.GONE);
			// 根据调节显示按钮
			if ("true".equals(mData.get(position).get("getValid"))) {
				holder.caozuolant.setVisibility(View.VISIBLE);
				holder.yipeihuob.setVisibility(View.VISIBLE);
				if ("true".equals(mData.get(position).get("getYanQi"))) {
					holder.yanqib.setVisibility(View.VISIBLE);
				}
			}
			if ("0".equals(mData.get(position).get("getStatus"))) {
				holder.caozuolant.setVisibility(View.VISIBLE);
				holder.bianjib.setVisibility(View.VISIBLE);
				holder.tijiaob.setVisibility(View.VISIBLE);
			}
			holder.bianjib.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View arg0) {
					try {
						FunctionOfActivity.progressDialogShow(THIS);
						Intent intent = new Intent(THIS,
								NewShipOrderActivity.class);
						String initId = mData.get(position).get("getId")
								.toString();
						String emptyShipPortText = mData.get(position)
								.get("getEShipPort").toString();
						String emptyShipDateText = mData.get(position)
								.get("getEShipTime").toString();
						String unitTypeText = mData.get(position)
								.get("getLoadton").toString();
						String goodsTypeText = mData.get(position)
								.get("getGoodsType").toString();
						String startPortText = mData.get(position)
								.get("getStartPort").toString();
						String endPortText = mData.get(position)
								.get("getEndPort").toString();
						String effectiveDateText = mData.get(position)
								.get("getEndTime").toString();
						String loadton = mData.get(position).get("getLoadton")
								.toString();
						String minPice = mData.get(position).get("getMinPice")
								.toString();
						String maxPice = mData.get(position).get("getMaxPice")
								.toString();
						intent.putExtra("getId", initId);
						intent.putExtra("getEShipPort", emptyShipPortText);
						intent.putExtra("getEShipTime", emptyShipDateText);
						intent.putExtra("getLoadton", unitTypeText);
						intent.putExtra("getGoodsType", goodsTypeText);
						intent.putExtra("getStartPort", startPortText);
						intent.putExtra("getEndPort", endPortText);
						intent.putExtra("getEndTime", effectiveDateText);
						intent.putExtra("loadton", loadton);
						intent.putExtra("bianji", true);
						intent.putExtra("minPice", minPice);
						intent.putExtra("maxPice", maxPice);
						startActivity(intent);
					} catch (Exception e) {

					}
				}
			});
			holder.tijiaob.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View arg0) {
					new AlertDialog.Builder(THIS)
							.setMessage("是否确认发布该船源？")
							.setTitle("提示")
							.setIcon(android.R.drawable.ic_dialog_info)
							.setPositiveButton("是",
									new DialogInterface.OnClickListener() {
										@Override
										public void onClick(
												DialogInterface dialog,
												int which) {
											try {
												String taskId = mData
														.get(position)
														.get("getId")
														.toString();
												String emptyShipPortText = mData
														.get(position)
														.get("getEShipPort")
														.toString();
												String emptyShipDateText = mData
														.get(position)
														.get("getEShipTime")
														.toString();
												String unitTypeText = mData
														.get(position)
														.get("getLoadton")
														.toString();
												String goodsTypeText = mData
														.get(position)
														.get("getGoodsType")
														.toString();
												String startPortText = mData
														.get(position)
														.get("getStartPort")
														.toString();
												String endPortText = mData
														.get(position)
														.get("getEndPort")
														.toString();
												String effectiveDateText = mData
														.get(position)
														.get("getEndTime")
														.toString();
												String minPice = mData
														.get(position)
														.get("getMinPice")
														.toString();
												String maxPice = mData
														.get(position)
														.get("getMaxPice")
														.toString();
												InitDatasDaoImpl.submitShipOrderAction(
														THIS, spu.getShip_id(),
														unitTypeText,
														startPortText,
														endPortText,
														effectiveDateText,
														goodsTypeText, maxPice,
														minPice,
														emptyShipPortText,
														emptyShipDateText,
														spu.getShip_name(),
														taskId);
											} catch (Exception e) {
												progressDialog.dismiss();
												FunctionOfActivity
														.makeToaskShow(THIS,
																"请求异常");

											}
										}
									}).setNegativeButton("取消", null).show();

				}
			});
			holder.yanqib.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View arg0) {

					try {
						/**
						 * 初始化显示时间
						 */
						int year = 0;
						int month = 0;
						int day = 0;
						try {
							String thisDate = mData.get(position)
									.get("getEndTime").toString();
							year = Integer.parseInt(thisDate.substring(0,
									thisDate.indexOf("-")));
							month = Integer.parseInt(thisDate.substring(
									thisDate.indexOf("-") + 1,
									thisDate.lastIndexOf("-")));
							day = Integer.parseInt(thisDate.substring(
									thisDate.lastIndexOf("-") + 1,
									thisDate.length()));
						} catch (Exception e) {
							year = Integer.parseInt(FunctionOfActivity
									.getYearFromDate());
							month = Integer.parseInt(FunctionOfActivity
									.getMonthFromDate());
							day = Integer.parseInt(FunctionOfActivity
									.getDayFromDate());

						}
						// 年月日时间选择器
						DatePickerDialog datePickerLog = new DatePickerDialog(
								THIS, new OnDateSetListener() {
									boolean mFired = true;

									@Override
									public void onDateSet(DatePicker view,
											final int year, int monthOfYear,
											int dayOfMonth) {
										int mountOfYearShow = monthOfYear + 1;
										final String month = FunctionOfActivity
												.addZero(mountOfYearShow + "");
										final String day = FunctionOfActivity
												.addZero(dayOfMonth + "");
										// 只能选择今天后的日期
										if (FunctionOfActivity
												.checkDataIsAfterToday(THIS,
														year, month, day)) {
											FunctionOfActivity
													.makeToaskShow(
															THIS,
															"请选择"
																	+ FunctionOfActivity
																			.getDayFromDateAddOneDay()
																	+ "号之后的日期");
										} else {
											// 4.2版本后可能会触发两次onDateSet，此处过滤
											if (mFired) {
												// 选择日期后，弹窗再次让客户确认
												new AlertDialog.Builder(THIS)
														.setTitle("提示")
														.setMessage(
																"延期到："
																		+ year
																		+ "-"
																		+ month
																		+ "-"
																		+ day
																		+ "\n您是否确认延期？")
														.setIcon(
																android.R.drawable.ic_dialog_info)
														.setPositiveButton(
																"是",
																new DialogInterface.OnClickListener() {
																	@Override
																	public void onClick(
																			DialogInterface dialog,
																			int which) {
																		InitDatasDaoImpl
																				.submitShipOrderYanQi(
																						THIS,
																						mData.get(
																								position)
																								.get("getId")
																								.toString(),
																						(year
																								+ "-"
																								+ month
																								+ "-" + day));

																	}
																})
														.setNegativeButton(
																"取消", null)
														.show();
												mFired = false;
											} else {
												return;
											}
										}
									}
								}, year, month - 1, day);
						datePickerLog.show();
					} catch (Exception e) {
						progressDialog.dismiss();
						FunctionOfActivity.makeToaskShow(THIS, "请求异常");

					}

				}
			});
			holder.yipeihuob.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View arg0) {
					new AlertDialog.Builder(THIS)
							.setTitle("提示")
							.setMessage("是否确认已配货？")
							.setIcon(android.R.drawable.ic_dialog_info)
							.setPositiveButton("是",
									new DialogInterface.OnClickListener() {
										@Override
										public void onClick(
												DialogInterface dialog,
												int which) {
											try {
												InitDatasDaoImpl
														.submitShipOrderYiPeiHuo(
																THIS,
																mData.get(
																		position)
																		.get("getId")
																		.toString());
											} catch (Exception e) {
												progressDialog.dismiss();
												FunctionOfActivity
														.makeToaskShow(THIS,
																"请求异常");

											}
										}
									}).setNegativeButton("取消", null).show();
				}
			});
			return convertView;
		}
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
			FunctionOfActivity.progressDialogShow(THIS);
			startActivity(new Intent(THIS, MainActivity.class));
			return true;
		}
		return super.onKeyDown(keyCode, event);
	}

}
